package org.agony2d.gpu.supportClasses.textures {
	import flash.display.BitmapData;
	import flash.display3D.Context3DTextureFormat;
	import flash.display3D.textures.Texture;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	import org.agony2d.core.agony_internal;
	import org.agony2d.debug.Logger;
	import org.agony2d.gpu.core.AAManager;
	import org.agony2d.gpu.core.NodeAA;
	
	use namespace agony_internal;
	
public class FullTexture extends TextureProxy {
	
	public function FullTexture( name:String ) {
		super(name)
	}
	
	agony_internal function reset( data:BitmapData, mipmapEnabled:Boolean, optimizeForRenderToTexture:Boolean ) : void {
		var AWidth:int, AHeight:int
		var BWidth:int, BHeight:int
		var currentWidth:int, currentHeight:int, level:int
		var BA:BitmapData
		
		Logger.reportMessage(this, "reset: " + m_name)
		
		m_regionList = {}
		
		AWidth        =  data.width
		AHeight       =  data.height
		BWidth        =  getNextPowerOfTwo(AWidth)
		BHeight       =  getNextPowerOfTwo(AHeight)
		m_rawTexture  =  AAManager.g_context3d.createTexture(BWidth, BHeight, Context3DTextureFormat.BGRA, optimizeForRenderToTexture)
		if (BWidth > AWidth || BHeight > AHeight) {
			BA = new BitmapData(BWidth, BHeight, true, 0x0)
			BA.copyPixels(data, data.rect, g_zeroPoint)
			data = BA
			m_realityWidth = AWidth
			m_realityHeight = AHeight
			m_fullWidth = BWidth
			m_fullHeight = BHeight
		}
		else {
			m_fullWidth = m_realityWidth = BWidth
			m_fullHeight = m_realityHeight = BHeight
		}
		m_rawTexture.uploadFromBitmapData(data)
		if (mipmapEnabled && data.width > 1 && data.height > 1) {
			level = 1
			currentWidth  = data.width  >> 1
			currentHeight = data.height >> 1
			BA = new BitmapData(currentWidth, currentHeight, true, 0x0)
			cachedRect.setTo(0, 0, currentWidth, currentHeight)
			cachedMatrix.setTo(.5, 0, 0, .5, 0, 0)
			while (currentWidth >= 1 || currentHeight >= 1) {
				BA.fillRect(cachedRect, 0x0)
				BA.draw(data, cachedMatrix, null, null, null, true)
				m_rawTexture.uploadFromBitmapData(BA, level++)
				currentWidth  >>= 1
				currentHeight >>= 1
				cachedRect.setTo(0, 0, currentWidth, currentHeight)
				cachedMatrix.scale(.5, .5)
			}
		}
	}
	
	agony_internal function addRegion( regionName:String, regionRect:Rectangle ) : void {
		if (m_regionList[regionName] || regionName == FULL_TEX) {
			Logger.reportError(this, "addRegion", "repeated region name [ " + regionName + " ]...!!")
		}
		m_regionList[regionName] = new RegionTexture(this, regionRect, regionName)
	}
	
	agony_internal function getTexture( name:String ) : TextureProxy {
		return (name == FULL_TEX) ? this : m_regionList[name]
	}
	
	
	agony_internal static const FULL_TEX:String = "fullTex"
	
	agony_internal var m_regionList:Object
	agony_internal var m_mipmapEnabled:Boolean
	
}
}